package com.hzb.controoler;

import com.hzb.entity.User;
import com.hzb.entity.UserFile;
import com.hzb.service.UserFileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 功能描述
 *
 * @author 和振斌
 * @date 2020/7/31
 * @return
 */
@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private UserFileService userFileService;




    /**返回当前用户的所有文件列表---json
     * */
    /**展现所有文件
     * */
    @GetMapping("showAllJSON")
    @ResponseBody
    public List<UserFile> findAllJSON(Model model, HttpSession session){
        User user= (User) session.getAttribute("user");
        List<UserFile> files = userFileService.findByUserId(user.getId());
        return files;
    }
    /**删除文件信息*/
    @GetMapping("delete")
    public String delete(Integer id) throws IOException {
        //根据id查询信息
        UserFile userFile = userFileService.findFileById(id);
        //删除文件
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        File file = new File(realpath, userFile.getNewFileName());
        if(file.exists())file.delete();//立即删除
        //删除数据库中记录
        userFileService.delete(id);
        return "redirect:/file/showAll";
    }
    /**文件下载*/

    @GetMapping("download")
    public void download(String openStyle,Integer id, HttpServletResponse response) throws IOException {
       //获取打开方式
        openStyle=openStyle==null?"attachment":openStyle;
        //获取文件信息
       UserFile userFile= userFileService.findFileById(id);
       //更新下载次数
        if("attachment".equals(openStyle)){
            userFile.setDowncounts(userFile.getDowncounts()+1);
            userFileService.update(userFile);
        }
       //根据文件信息中文件的名字和文件的存储路径获取文件的输入流
        String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
        //获取文件输入流
        FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(userFile.getOldFileName(),"UTF-8"));

        //获取响应输出流
        ServletOutputStream os=response.getOutputStream();
        //文件拷贝
        IOUtils.copy(is,os);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }

    /**上传文件
     * */
    @PostMapping("upload")
    public String upload(MultipartFile file,HttpSession session) throws IOException {
       //获取上传用户的id
        User user = (User) session.getAttribute("user");
        //获取文件的原始名称
        String oldFileName=file.getOriginalFilename();
        //获取文件后缀
        String ext = "."+FilenameUtils.getExtension(file.getOriginalFilename());
        //生成新的文件名
        String newFileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+ext;
        //文件的大小
        Long size = file.getSize();
        //文件类型
        String type = file.getContentType();
        //根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
        String dataFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath= realPath+"/"+ dataFormat;
         File dateDir=new File(dateDirPath);
        if(!dateDir.exists())
            //创建
            dateDir.mkdirs();

        //处理文件上传
       file.transferTo(new File(dateDir,newFileName));
        //将文件信息存储到数据库中
        UserFile userFile = new UserFile();
        userFile.setOldFileName(oldFileName);
        userFile.setNewFileName(newFileName);
        userFile.setExt(ext);
        userFile.setSize(String.valueOf(size));
        userFile.setType(type);
        userFile.setPath("/files/"+dataFormat);
        System.out.println(user.getId());
        userFile.setUserid(user.getId());


        userFileService.save(userFile);
        return "redirect:/file/showAll";
    }

    /**展现所有文件
     * */
    @GetMapping("showAll")
    public String findAll(Model model, HttpSession session){
        User user= (User) session.getAttribute("user");
        List<UserFile> files = userFileService.findByUserId(user.getId());
        model.addAttribute("files",files);
        return "showAll";
    }
}
